import { parseDate, formatDate, addDays, addMonths, daysBetween } from './dateUtils.js';

/**
 * 从身份证号码中提取性别和出生日期
 * @param {string} idCardNumber - 18位身份证号码
 * @returns {object} - 包含性别和出生日期的对象
 */
function extractFromIdCard(idCardNumber) {
    if (!idCardNumber || idCardNumber.length !== 18) {
        return { gender: null, birthDate: null };
    }
    
    try {
        // 提取出生日期 (第7-14位)
        const year = idCardNumber.substring(6, 10);
        const month = idCardNumber.substring(10, 12);
        const day = idCardNumber.substring(12, 14);
        const birthDate = `${year}-${month}-${day}`;
        
        // 提取性别 (第17位，奇数为男性，偶数为女性)
        const genderCode = parseInt(idCardNumber.charAt(16));
        const gender = genderCode % 2 === 1 ? '男' : '女';
        
        return { gender, birthDate };
    } catch (error) {
        return { gender: null, birthDate: null };
    }
}

/**
 * 检查是否满18周岁
 * @param {string} birthDate - 出生日期
 * @param {string} targetDate - 目标日期
 * @returns {boolean}
 */
function isOver18(birthDate, targetDate) {
    const birth = parseDate(birthDate);
    const target = parseDate(targetDate);
    if (!birth || !target) return false;
    
    const eighteenYearsLater = addMonths(birth, 12 * 18);
    return target >= eighteenYearsLater;
}

/**
 * 检查每三个月是否有思想汇报 (最终修正版)
 * @param {Array} reports - 思想汇报数组
 * @param {string} startDate - 开始日期
 * @param {string} endDate - 结束日期
 * @returns {object} - 包含验证结果的对象
 */
function checkQuarterlyReports(reports, startDate, endDate) {
    const start = parseDate(startDate);
    const end = parseDate(endDate);
    
    if (!start || !end || start > end) { // 调整了日期判断，允许同一天
        return { isValid: false, missingPeriods: [], totalPeriods: 0, actualReports: (reports || []).length };
    }
    
    const missingPeriods = [];
    const reportDates = reports.map(r => parseDate(r.signatureDate)).filter(d => d).sort((a, b) => a - b);
    
    // --- 核心逻辑重构 ---

    let currentPeriodStart = new Date(start); // 从总的开始日期，作为第一个周期的起始点
    let totalPeriods = 0; // 用于累计总共需要多少个周期/汇报
    
    // 循环的条件是：只要当前计算的周期起始点还在总的结束日期之前（或同一天），就继续划分
    while (currentPeriodStart <= end) {
        totalPeriods++; // 每进入一次循环，就意味着有一个必须检查的周期
        
        // 1. 计算出当前周期的理论结束日期（包含当天）
        // 例如：如果 currentPeriodStart 是 2023-01-15，则理论结束点是 2023-04-14
        const theoreticalPeriodEnd = addDays(addMonths(currentPeriodStart, 3), -1);
        
        // 2. 确定当前周期的实际结束日期（包含当天）
        // 如果理论结束日期超过了总的结束日期，则以总的结束日期为准
        const actualPeriodEnd = (theoreticalPeriodEnd < end) ? theoreticalPeriodEnd : new Date(end);

        // 3. 在这个 [开始, 结束] 的闭区间内，检查是否存在至少一篇汇报
        const hasReportInPeriod = reportDates.some(reportDate => 
            reportDate >= currentPeriodStart && reportDate <= actualPeriodEnd
        );
        
        // 4. 如果没有找到汇报，则记录这个缺失的周期
        if (!hasReportInPeriod) {
            missingPeriods.push({
                start: formatDate(currentPeriodStart),
                end: formatDate(actualPeriodEnd)
            });
        }
        
        // 5. 准备下一个周期的起始点：直接在当前周期起始点的基础上加3个月
        // 这样可以保证每个周期的划分都是从最开始的时间点严格按3个月递增的
        currentPeriodStart = addMonths(currentPeriodStart, 3);
    }
    
    return {
        isValid: missingPeriods.length === 0,
        missingPeriods, // 精确列出缺失的周期
        totalPeriods,   // 准确计算出应有的汇报总数
        actualReports: reportDates.length
    };
}
/**
 * 主验证函数
 * @param {object} member - 党员信息对象
 * @returns {object} - 验证结果对象
 */
export function validateMember(member) {

    

    const verifyMember = {};
    
    // 从身份证号码提取信息
    const idCardInfo = extractFromIdCard(member.idCardNumber);
    
    // 1. 验证基本信息
    verifyMember.basicInfo = [];
    
    // 验证身份证号码
    if (!member.idCardNumber || member.idCardNumber.length !== 18) {
        verifyMember.basicInfo.push({
            key: 'idCardNumber',
            level: 'error',
            message: '身份证号码格式不正确，应为18位数字字符串'
        });
    } else {
        verifyMember.basicInfo.push({
            key: 'idCardNumber',
            level: 'success',
            message: '身份证号码格式正确'
        });
    }
    
    // 验证性别是否与身份证号码一致
    if (member.genderType && idCardInfo.gender) {
        if (member.genderType !== idCardInfo.gender) {
            verifyMember.basicInfo.push({
                key: 'genderType',
                level: 'error',
                message: `性别信息与身份证号码不匹配：当前填写"${member.genderType}"，身份证显示"${idCardInfo.gender}"，请核对后修改`
            });
        } else {
            verifyMember.basicInfo.push({
                key: 'genderType',
                level: 'success',
                message: '性别信息与身份证号码一致'
            });
        }
    } else if (!member.genderType) {
        verifyMember.basicInfo.push({
            key: 'genderType',
            level: 'info',
            message: idCardInfo.gender ? `性别信息未填写，建议填写：${idCardInfo.gender}` : '性别信息未填写'
        });
    }
    
    // 验证出生日期是否与身份证号码一致
    if (member.birthDate && idCardInfo.birthDate) {
        if (formatDate(member.birthDate) !== formatDate(idCardInfo.birthDate)) {
            verifyMember.basicInfo.push({
                key: 'birthDate',
                level: 'error',
                message: `出生日期与身份证号码不匹配：当前填写"${formatDate(member.birthDate)}"，身份证显示"${formatDate(idCardInfo.birthDate)}"，请核对后修改`
            });
        } else {
            verifyMember.basicInfo.push({
                key: 'birthDate',
                level: 'success',
                message: '出生日期与身份证号码一致'
            });
        }
    } else if (!member.birthDate) {
        verifyMember.basicInfo.push({
            key: 'birthDate',
            level: 'info',
            message: idCardInfo.birthDate ? `出生日期未填写，建议填写：${formatDate(idCardInfo.birthDate)}` : '出生日期未填写'
        });
    }
    
   // 2. 验证党支部历史连续性
verifyMember.partyBranchHistory = [];

if (!member.partyBranchHistory || member.partyBranchHistory.length === 0) {
    // 情况1：没有任何历史记录 (n=0)，返回一个长度为 0+1=1 的数组
    verifyMember.partyBranchHistory.push({
        key: 'partyBranchHistory',
        level: 'info',
        message: '党支部历史记录未填写，建议按时间顺序填写所有党组织关系转移记录'
    });
} else {
    // 按开始日期对历史记录进行排序
    const sortedHistory = member.partyBranchHistory
        .filter(h => h.startDate)
        .sort((a, b) => parseDate(a.startDate) - parseDate(b.startDate));

    const n = sortedHistory.length;
    // 创建一个数组，用于存放 n 条记录各自的状态
    const recordStatuses = []; 
    let errorCount = 0;

    // 遍历每一条记录，生成其对应的状态信息
    for (let i = 0; i < n; i++) {
        // 对第一条记录的特殊处理
        if (i === 0) {
            recordStatuses.push({
                key: `partyBranchHistory[${i}]`,
                level: 'success',
                message: '第1条记录作为起始记录有效'
            });
            continue; // 继续下一次循环
        }

        // 验证当前记录(i)与前一条记录(i-1)的连续性
        const prevEnd = parseDate(sortedHistory[i - 1].endDate);
        const currentStart = parseDate(sortedHistory[i].startDate);
        
        if (prevEnd && currentStart) {
            const expectedStart = addDays(prevEnd, 1);
            if (currentStart.getTime() !== expectedStart.getTime()) {
                // 时间不连续 -> 记录错误
                errorCount++;
                recordStatuses.push({
                    key: `partyBranchHistory[${i}]`,
                    level: 'error',
                    message: `时间不连续：应从 ${formatDate(expectedStart)} 开始`
                });
            } else {
                // 时间连续 -> 记录成功
                recordStatuses.push({
                    key: `partyBranchHistory[${i}]`,
                    level: 'success',
                    message: '时间连续正确'
                });
            }
        } else {
            // 前一条记录缺少结束日期 -> 记录错误
            errorCount++;
            recordStatuses.push({
                key: `partyBranchHistory[${i}]`,
                level: 'error',
                message: `无法验证连续性，因前一记录缺少结束日期`
            });
        }
    }

    // 根据错误数量生成总的概览信息 (位置0)
    let summaryMessage;
    if (errorCount === 0) {
        summaryMessage = {
            key: 'partyBranchHistory',
            level: 'success',
            message: `党支部历史记录时间连续性正确，共${n}条有效记录`
        };
    } else {
        summaryMessage = {
            key: 'partyBranchHistory',
            level: 'error',
            message: `共发现 ${errorCount} 处问题，请检查下方高亮记录`
        };
    }

    // 组合最终结果：[总览信息, ...各条记录的状态]
    verifyMember.partyBranchHistory = [summaryMessage, ...recordStatuses];
}
    // 3. 验证入党申请书
    verifyMember.applicationForm = [];
    
    if (!member.applicationForm?.signatureDate) {
        verifyMember.applicationForm.push({
            key: 'signatureDate',
            level: 'info',
            message: '入党申请书落款时间未填写，这是入党流程的第一步'
        });
    } else {
        const birthDate = member.birthDate || idCardInfo.birthDate;
        if (birthDate) {
            const eighteenthBirthday = addMonths(parseDate(birthDate), 12 * 18);
            if (!isOver18(birthDate, member.applicationForm.signatureDate)) {
                verifyMember.applicationForm.push({
                    key: 'signatureDate',
                    level: 'error',
                    message: `入党申请书落款时间不符合年龄要求：当前日期${formatDate(member.applicationForm.signatureDate)}，需在满18周岁后（${formatDate(eighteenthBirthday)}及以后）`
                });
            } else {
                verifyMember.applicationForm.push({
                    key: 'signatureDate',
                    level: 'success',
                    message: `入党申请书落款时间符合要求（${formatDate(member.applicationForm.signatureDate)}）`
                });
            }
        } else {
            verifyMember.applicationForm.push({
                key: 'signatureDate',
                level: 'warning',
                message: '无法验证入党申请书年龄要求，请先填写出生日期'
            });
        }
    }
    
    // 4. 验证谈心谈话记录
    verifyMember.heartToHeartTalk = [];
    
    if (!member.heartToHeartTalk?.signatureDate) {
        verifyMember.heartToHeartTalk.push({
            key: 'signatureDate',
            level: 'info',
            message: '谈心谈话记录落款时间未填写，应在提交入党申请书后进行'
        });
    } else if (member.applicationForm?.signatureDate) {
        const applicationDate = parseDate(member.applicationForm.signatureDate);
        const talkDate = parseDate(member.heartToHeartTalk.signatureDate);
        const thirtyDaysLater = addDays(applicationDate, 30);
        
        if (talkDate < applicationDate) {
            verifyMember.heartToHeartTalk.push({
                key: 'signatureDate',
                level: 'error',
                message: `谈心谈话记录时间顺序错误：当前日期${formatDate(talkDate)}，应在入党申请书日期（${formatDate(applicationDate)}）之后`
            });
        } else if (talkDate > thirtyDaysLater) {
            verifyMember.heartToHeartTalk.push({
                key: 'signatureDate',
                level: 'error',
                message: `谈心谈话记录时间超出规定：当前日期${formatDate(talkDate)}，应在入党申请书后30天内（${formatDate(applicationDate)} - ${formatDate(thirtyDaysLater)}）`
            });
        } else {
            verifyMember.heartToHeartTalk.push({
                key: 'signatureDate',
                level: 'success',
                message: `谈心谈话记录时间符合要求（${formatDate(talkDate)}），在规定时间内完成`
            });
        }
    } else {
        verifyMember.heartToHeartTalk.push({
            key: 'signatureDate',
            level: 'warning',
            message: '无法验证谈心谈话记录时间要求，请先填写入党申请书落款时间'
        });
    }
    
    // 5. 验证积极分子推荐表
    verifyMember.activistRecommendation = [];
    
    const ar = member.activistRecommendation;
    if (!ar) {
        verifyMember.activistRecommendation.push({
            key: 'activistRecommendation',
            level: 'info',
            message: '积极分子推荐表未填写，应在提交入党申请书满6个月后进行'
        });
    } else {
        // 检查时间顺序：团支部推荐时间、填表时间、基层团委审批意见时间、校团委审核意见时间
        const dateSequence = [
            { key: 'branchRecommendDate', name: '团支部推荐时间', date: parseDate(ar.branchRecommendDate) },
            { key: 'formFillDate', name: '填表时间', date: parseDate(ar.formFillDate) },
            { key: 'baseCommitteeApprovalDate', name: '基层团委审批意见时间', date: parseDate(ar.baseCommitteeApprovalDate) },
            { key: 'schoolCommitteeReviewDate', name: '校团委审核意见时间', date: parseDate(ar.schoolCommitteeReviewDate) }
        ];
        
        const validDates = dateSequence.filter(d => d.date);
        let timeOrderCorrect = true;
        
        for (let i = 1; i < validDates.length; i++) {
            if (validDates[i].date < validDates[i-1].date) {
                timeOrderCorrect = false;
                verifyMember.activistRecommendation.push({
                    key: validDates[i].key,
                    level: 'error',
                    message: `时间顺序错误：${validDates[i].name}（${formatDate(validDates[i].date)}）应在${validDates[i-1].name}（${formatDate(validDates[i-1].date)}）之后`
                });
            }
        }
        
        if (timeOrderCorrect && validDates.length >= 4) {
            verifyMember.activistRecommendation.push({
                key: 'timeOrder',
                level: 'success',
                message: '积极分子推荐表各环节时间顺序正确'
            });
        }
        
        // 验证填表时间是否在入党申请书后6个月
        if (ar.formFillDate && member.applicationForm?.signatureDate) {
            const applicationDate = parseDate(member.applicationForm.signatureDate);
            const fillDate = parseDate(ar.formFillDate);
            const sixMonthsLater = addMonths(applicationDate, 6);
            
            if (fillDate < sixMonthsLater) {
                verifyMember.activistRecommendation.push({
                    key: 'formFillDate',
                    level: 'error',
                    message: `填表时间过早：当前日期${formatDate(fillDate)}，应在提交入党申请书满6个月后（${formatDate(sixMonthsLater)}及以后）`
                });
            } else {
                verifyMember.activistRecommendation.push({
                    key: 'formFillDate',
                    level: 'success',
                    message: `填表时间符合6个月要求（${formatDate(fillDate)}）`
                });
            }
        } else if (ar.formFillDate && !member.applicationForm?.signatureDate) {
            verifyMember.activistRecommendation.push({
                key: 'formFillDate',
                level: 'warning',
                message: '无法验证6个月要求，请先填写入党申请书落款时间'
            });
        }
        
        // 验证确定为发展对象时间是否在校团委审核时间一年后
        if (ar.developmentTargetDate && ar.schoolCommitteeReviewDate) {
            const reviewDate = parseDate(ar.schoolCommitteeReviewDate);
            const targetDate = parseDate(ar.developmentTargetDate);
            const oneYearLater = addMonths(reviewDate, 12);
            
            if (targetDate < oneYearLater) {
                verifyMember.activistRecommendation.push({
                    key: 'developmentTargetDate',
                    level: 'error',
                    message: `确定发展对象时间过早：当前日期${formatDate(targetDate)}，应在校团委审核时间满一年后（${formatDate(oneYearLater)}及以后）`
                });
            } else {
                verifyMember.activistRecommendation.push({
                    key: 'developmentTargetDate',
                    level: 'success',
                    message: `确定发展对象时间符合一年要求（${formatDate(targetDate)}）`
                });
            }
        }
    }
    
    // 6. 验证积极分子考察表
    verifyMember.activistAssessment = [];
    
    const aa = member.activistAssessment;
    if (!aa) {
        verifyMember.activistAssessment.push({
            key: 'activistAssessment',
            level: 'info',
            message: '积极分子考察表未填写，应与积极分子推荐表同步完成'
        });
    } else {
        // 验证列为积极分子时间是否与校团委审核意见时间一致
        if (aa.activistDesignationDate && ar?.schoolCommitteeReviewDate) {
            if (formatDate(aa.activistDesignationDate) !== formatDate(ar.schoolCommitteeReviewDate)) {
                verifyMember.activistAssessment.push({
                    key: 'activistDesignationDate',
                    level: 'error',
                    message: `列为积极分子时间不一致：当前日期${formatDate(aa.activistDesignationDate)}，应与积极分子推荐表中校团委审核意见时间（${formatDate(ar.schoolCommitteeReviewDate)}）保持一致`
                });
            } else {
                verifyMember.activistAssessment.push({
                    key: 'activistDesignationDate',
                    level: 'success',
                    message: `列为积极分子时间正确（${formatDate(aa.activistDesignationDate)}）`
                });
            }
        } else if (aa.activistDesignationDate && !ar?.schoolCommitteeReviewDate) {
            verifyMember.activistAssessment.push({
                key: 'activistDesignationDate',
                level: 'warning',
                message: '无法验证列为积极分子时间，请先填写积极分子推荐表中的校团委审核意见时间'
            });
        }
        
        // 验证主要表现落款日期是否与列为积极分子时间一致
        if (aa.secretarySignatureDate && aa.activistDesignationDate) {
            if (formatDate(aa.secretarySignatureDate) !== formatDate(aa.activistDesignationDate)) {
                verifyMember.activistAssessment.push({
                    key: 'secretarySignatureDate',
                    level: 'error',
                    message: `主要表现落款日期不一致：当前日期${formatDate(aa.secretarySignatureDate)}，应与列为积极分子时间（${formatDate(aa.activistDesignationDate)}）保持一致`
                });
            } else {
                verifyMember.activistAssessment.push({
                    key: 'secretarySignatureDate',
                    level: 'success',
                    message: `主要表现落款日期正确（${formatDate(aa.secretarySignatureDate)}）`
                });
            }
        }
        
        // 验证培养考察写实记录每三个月要求
        if (aa.assessmentRecords && aa.activistDesignationDate && ar?.developmentTargetDate) {
            const records = aa.assessmentRecords.filter(r => r.branchOpinionDate);
            const checkResult = checkQuarterlyReports(
                records.map(r => ({ signatureDate: r.branchOpinionDate })),
                aa.activistDesignationDate,
                ar.developmentTargetDate
            );
            
            if (!checkResult.isValid) {
                verifyMember.activistAssessment.push({
                    key: 'assessmentRecords',
                    level: 'error',
                    message: `培养考察写实记录不足：应有${checkResult.totalPeriods}份记录，实际${checkResult.actualReports}份，缺少${checkResult.missingPeriods.length}个时期的记录`
                });
                checkResult.missingPeriods.forEach((period, index) => {
                    verifyMember.activistAssessment.push({
                        key: `assessmentRecords_missing_${index}`,
                        level: 'error',
                        message: `缺少时期：${period.start} 至 ${period.end}`
                    });
                });
            } else {
                verifyMember.activistAssessment.push({
                    key: 'assessmentRecords',
                    level: 'success',
                    message: `培养考察写实记录完整（${checkResult.actualReports}份），符合每三个月一次的要求`
                });
            }
        }
        
        // 验证支委会意见日期与群众座谈意见日期关系
        if (aa.committeeOpinionDate && aa.massDiscussionDate) {
            const committeeDate = parseDate(aa.committeeOpinionDate);
            const discussionDate = parseDate(aa.massDiscussionDate);
            
            if (committeeDate <= discussionDate) {
                verifyMember.activistAssessment.push({
                    key: 'committeeOpinionDate',
                    level: 'error',
                    message: `时间顺序错误：支委会意见日期（${formatDate(committeeDate)}）应在群众座谈意见日期（${formatDate(discussionDate)}）之后`
                });
            } else {
                verifyMember.activistAssessment.push({
                    key: 'committeeOpinionDate',
                    level: 'success',
                    message: `支委会意见日期正确（${formatDate(committeeDate)}），在群众座谈后进行`
                });
            }
        }
    }
    
    // 7. 验证积极分子时期思想汇报
    verifyMember.activistThoughtReports = [];
    
    if (!member.activistThoughtReports || member.activistThoughtReports.length === 0) {
        verifyMember.activistThoughtReports.push({
            key: 'activistThoughtReports',
            level: 'info',
            message: '积极分子时期思想汇报未填写，应从被列为积极分子开始，每3个月提交一份'
        });
    } else if (aa?.activistDesignationDate && ar?.developmentTargetDate) {
        const checkResult = checkQuarterlyReports(
            member.activistThoughtReports,
            aa.activistDesignationDate,
            ar.developmentTargetDate
        );
        
        if (!checkResult.isValid) {
            verifyMember.activistThoughtReports.push({
                key: 'activistThoughtReports',
                level: 'error',
                message: `积极分子时期思想汇报不足：从${formatDate(aa.activistDesignationDate)}到${formatDate(ar.developmentTargetDate)}期间应有${checkResult.totalPeriods}份汇报，实际${checkResult.actualReports}份`
            });
            checkResult.missingPeriods.forEach((period, index) => {
                verifyMember.activistThoughtReports.push({
                    key: `missing_period_${index}`,
                    level: 'error',
                    message: `缺少汇报时期：${period.start} 至 ${period.end}`
                });
            });
        } else {
            verifyMember.activistThoughtReports.push({
                key: 'activistThoughtReports',
                level: 'success',
                message: `积极分子时期思想汇报完整（${checkResult.actualReports}份），符合每三个月一次的要求`
            });
        }
    } else {
        verifyMember.activistThoughtReports.push({
            key: 'activistThoughtReports',
            level: 'warning',
            message: '无法验证思想汇报时间要求，请先完善积极分子考察表和推荐表的相关时间'
        });
    }
    
    // 8. 验证群众意见
    verifyMember.massOpinion = [];
    
    if (!member.massOpinion?.signatureDate) {
        verifyMember.massOpinion.push({
            key: 'signatureDate',
            level: 'info',
            message: '群众意见落款日期未填写，应在确定发展对象前进行群众座谈'
        });
    } else {
        // 验证是否与积极分子考察表中的群众座谈意见日期一致
        if (aa?.massDiscussionDate) {
            if (formatDate(member.massOpinion.signatureDate) !== formatDate(aa.massDiscussionDate)) {
                verifyMember.massOpinion.push({
                    key: 'signatureDate',
                    level: 'error',
                    message: `群众意见日期不一致：当前日期${formatDate(member.massOpinion.signatureDate)}，应与积极分子考察表中群众座谈意见日期（${formatDate(aa.massDiscussionDate)}）保持一致`
                });
            } else {
                verifyMember.massOpinion.push({
                    key: 'signatureDate',
                    level: 'success',
                    message: `群众意见日期正确（${formatDate(member.massOpinion.signatureDate)}）`
                });
            }
        }
        
        // 验证是否在确定发展对象日期之前
        if (ar?.developmentTargetDate) {
            const massDate = parseDate(member.massOpinion.signatureDate);
            const targetDate = parseDate(ar.developmentTargetDate);
            
            if (massDate >= targetDate) {
                verifyMember.massOpinion.push({
                    key: 'signatureDate',
                    level: 'error',
                    message: `群众意见时间顺序错误：当前日期${formatDate(massDate)}，应在确定发展对象日期（${formatDate(targetDate)}）之前`
                });
            } else {
                verifyMember.massOpinion.push({
                    key: 'signatureDate',
                    level: 'success',
                    message: `群众意见时间顺序正确，在确定发展对象前完成`
                });
            }
        }
    }
    
    // 9. 验证自传
    verifyMember.autobiography = [];
    
    if (!member.autobiography?.signatureDate) {
        verifyMember.autobiography.push({
            key: 'signatureDate',
            level: 'info',
            message: '自传落款日期未填写，应在确定为发展对象前完成'
        });
    } else if (ar?.developmentTargetDate) {
        const autoDate = parseDate(member.autobiography.signatureDate);
        const targetDate = parseDate(ar.developmentTargetDate);
        
        if (autoDate >= targetDate) {
            verifyMember.autobiography.push({
                key: 'signatureDate',
                level: 'error',
                message: `自传时间顺序错误：当前日期${formatDate(autoDate)}，应在确定发展对象日期（${formatDate(targetDate)}）之前`
            });
        } else {
            verifyMember.autobiography.push({
                key: 'signatureDate',
                level: 'success',
                message: `自传落款日期正确（${formatDate(autoDate)}），在确定发展对象前完成`
            });
        }
    } else {
        verifyMember.autobiography.push({
            key: 'signatureDate',
            level: 'warning',
            message: '无法验证自传时间要求，请先填写确定发展对象日期'
        });
    }
    
    // 10. 验证政审外调
    verifyMember.externalInvestigations = [];
    
    if (!member.externalInvestigations || member.externalInvestigations.length === 0) {
        verifyMember.externalInvestigations.push({
            key: 'externalInvestigations',
            level: 'info',
            message: '政审外调记录未填写，应在确定为发展对象后、政审综合前完成'
        });
    } else {
        let allValid = true;
        
        member.externalInvestigations.forEach((inv, index) => {
            if (!inv.signatureDate) {
                verifyMember.externalInvestigations.push({
                    key: `externalInvestigations[${index}].signatureDate`,
                    level: 'info',
                    message: `第${index + 1}份外调记录落款日期未填写`
                });
                allValid = false;
            } else {
                // 验证是否在确定发展对象日期之后
                if (ar?.developmentTargetDate) {
                    const invDate = parseDate(inv.signatureDate);
                    const targetDate = parseDate(ar.developmentTargetDate);
                    
                    if (invDate <= targetDate) {
                        verifyMember.externalInvestigations.push({
                            key: `externalInvestigations[${index}].signatureDate`,
                            level: 'error',
                            message: `第${index + 1}份外调记录时间顺序错误：当前日期${formatDate(invDate)}，应在确定发展对象日期（${formatDate(targetDate)}）之后`
                        });
                        allValid = false;
                    }
                }
                
                // 验证是否在政审综合日期之前
                if (member.comprehensiveReview?.signatureDate) {
                    const invDate = parseDate(inv.signatureDate);
                    const reviewDate = parseDate(member.comprehensiveReview.signatureDate);
                    
                    if (invDate >= reviewDate) {
                        verifyMember.externalInvestigations.push({
                            key: `externalInvestigations[${index}].signatureDate`,
                            level: 'error',
                            message: `第${index + 1}份外调记录时间顺序错误：当前日期${formatDate(invDate)}，应在政审综合日期（${formatDate(reviewDate)}）之前`
                        });
                        allValid = false;
                    }
                }
            }
        });
        
        if (allValid && member.externalInvestigations.length > 0) {
            verifyMember.externalInvestigations.splice(0, 0, {
                key: 'externalInvestigations',
                level: 'success',
                message: `政审外调记录时间正确（共${member.externalInvestigations.length}份），在规定时间范围内完成`
            });
        }
    }
    
    // 11. 验证政审综合
    verifyMember.comprehensiveReview = [];
    
    if (!member.comprehensiveReview?.signatureDate) {
        verifyMember.comprehensiveReview.push({
            key: 'signatureDate',
            level: 'info',
            message: '政审综合落款日期未填写，应在完成自传、群众意见和政审外调后进行'
        });
    } else {
        let isValid = true;
        const dependencies = [];
        
        // 验证是否在自传日期之后
        if (member.autobiography?.signatureDate) {
            const reviewDate = parseDate(member.comprehensiveReview.signatureDate);
            const autoDate = parseDate(member.autobiography.signatureDate);
            
            if (reviewDate <= autoDate) {
                verifyMember.comprehensiveReview.push({
                    key: 'signatureDate',
                    level: 'error',
                    message: `政审综合时间顺序错误：当前日期${formatDate(reviewDate)}，应在自传日期（${formatDate(autoDate)}）之后`
                });
                isValid = false;
            } else {
                dependencies.push(`自传（${formatDate(autoDate)}）`);
            }
        }
        
        // 验证是否在群众意见日期之后
        if (member.massOpinion?.signatureDate) {
            const reviewDate = parseDate(member.comprehensiveReview.signatureDate);
            const massDate = parseDate(member.massOpinion.signatureDate);
            
            if (reviewDate <= massDate) {
                verifyMember.comprehensiveReview.push({
                    key: 'signatureDate',
                    level: 'error',
                    message: `政审综合时间顺序错误：当前日期${formatDate(reviewDate)}，应在群众意见日期（${formatDate(massDate)}）之后`
                });
                isValid = false;
            } else {
                dependencies.push(`群众意见（${formatDate(massDate)}）`);
            }
        }
        
        if (isValid && dependencies.length > 0) {
            verifyMember.comprehensiveReview.push({
                key: 'signatureDate',
                level: 'success',
                message: `政审综合日期正确（${formatDate(member.comprehensiveReview.signatureDate)}），在${dependencies.join('、')}之后完成`
            });
        }
    }
    
    // 12. 验证发展对象预审
    verifyMember.developmentTargetPrereview = [];
    
    if (!member.developmentTargetPrereview?.signatureDate) {
        verifyMember.developmentTargetPrereview.push({
            key: 'signatureDate',
            level: 'info',
            message: '预审日期未填写，应在政审综合完成后进行'
        });
    } else if (member.comprehensiveReview?.signatureDate) {
        const prereviewDate = parseDate(member.developmentTargetPrereview.signatureDate);
        const reviewDate = parseDate(member.comprehensiveReview.signatureDate);
        
        if (prereviewDate <= reviewDate) {
            verifyMember.developmentTargetPrereview.push({
                key: 'signatureDate',
                level: 'error',
                message: `预审时间顺序错误：当前日期${formatDate(prereviewDate)}，应在政审综合日期（${formatDate(reviewDate)}）之后`
            });
        } else {
            verifyMember.developmentTargetPrereview.push({
                key: 'signatureDate',
                level: 'success',
                message: `预审日期正确（${formatDate(prereviewDate)}），在政审综合后进行`
            });
        }
    } else {
        verifyMember.developmentTargetPrereview.push({
            key: 'signatureDate',
            level: 'warning',
            message: '无法验证预审时间要求，请先填写政审综合落款日期'
        });
    }
    
    // 13. 验证发展党员公示结果
    verifyMember.developmentPublicity = [];
    
    const dp = member.developmentPublicity;
    if (!dp?.startDate || !dp?.endDate) {
        verifyMember.developmentPublicity.push({
            key: 'developmentPublicity',
            level: 'info',
            message: '发展党员公示日期未填写，应进行5天公示'
        });
    } else {
        const startDate = parseDate(dp.startDate);
        const endDate = parseDate(dp.endDate);
        const days = daysBetween(startDate, endDate) + 1;
        
        if (days !== 5) {
            verifyMember.developmentPublicity.push({
                key: 'developmentPublicity',
                level: 'error',
                message: `发展党员公示时间不符合要求：当前公示${days}天（${formatDate(startDate)} - ${formatDate(endDate)}），应为5天`
            });
        } else {
            verifyMember.developmentPublicity.push({
                key: 'developmentPublicity',
                level: 'success',
                message: `发展党员公示时间正确（5天：${formatDate(startDate)} - ${formatDate(endDate)}）`
            });
        }
        
        // 验证落款日期是否为公示结束后第一天
        if (dp.signatureDate) {
            const signatureDate = parseDate(dp.signatureDate);
            const expectedDate = addDays(endDate, 1);
            
            if (signatureDate.getTime() !== expectedDate.getTime()) {
                verifyMember.developmentPublicity.push({
                    key: 'signatureDate',
                    level: 'error',
                    message: `公示结果落款日期错误：当前日期${formatDate(signatureDate)}，应为公示结束后第一天（${formatDate(expectedDate)}）`
                });
            } else {
                verifyMember.developmentPublicity.push({
                    key: 'signatureDate',
                    level: 'success',
                    message: `公示结果落款日期正确（${formatDate(signatureDate)}）`
                });
            }
        }
    }
    
    // 14. 验证入党志愿书
    verifyMember.applicationVolunteer = [];
    
    const av = member.applicationVolunteer;
    if (!av) {
        verifyMember.applicationVolunteer.push({
            key: 'applicationVolunteer',
            level: 'info',
            message: '入党志愿书未填写，应在发展党员公示结束后填写'
        });
    } else {
        // 验证本人签字落款是否在发展党员公示结束之后
        if (av.personalSignatureDate && dp?.endDate) {
            const personalDate = parseDate(av.personalSignatureDate);
            const publicityEndDate = parseDate(dp.endDate);
            
            if (personalDate <= publicityEndDate) {
                verifyMember.applicationVolunteer.push({
                    key: 'personalSignatureDate',
                    level: 'error',
                    message: `入党志愿书本人签字时间顺序错误：当前日期${formatDate(personalDate)}，应在发展党员公示结束（${formatDate(publicityEndDate)}）之后`
                });
            } else {
                verifyMember.applicationVolunteer.push({
                    key: 'personalSignatureDate',
                    level: 'success',
                    message: `入党志愿书本人签字时间正确（${formatDate(personalDate)}）`
                });
            }
        }
        
        // 验证接受预备党员表决情况汇总表日期是否一致
        if (av.branchMeetingSignatureDate && member.probationaryAcceptanceVoting?.signatureDate) {
            if (formatDate(av.branchMeetingSignatureDate) !== formatDate(member.probationaryAcceptanceVoting.signatureDate)) {
                verifyMember.applicationVolunteer.push({
                    key: 'branchMeetingSignatureDate',
                    level: 'error',
                    message: `支部大会决议日期不一致：当前日期${formatDate(av.branchMeetingSignatureDate)}，应与接受预备党员表决情况汇总表日期（${formatDate(member.probationaryAcceptanceVoting.signatureDate)}）保持一致`
                });
            } else {
                verifyMember.applicationVolunteer.push({
                    key: 'branchMeetingSignatureDate',
                    level: 'success',
                    message: `支部大会决议日期正确（${formatDate(av.branchMeetingSignatureDate)}）`
                });
            }
        }
    }
    
    // 15. 验证预备党员考察表
    verifyMember.probationaryAssessment = [];
    
    const pa = member.probationaryAssessment;
    if (!pa?.assessmentOpinions || pa.assessmentOpinions.length !== 2) {
        verifyMember.probationaryAssessment.push({
            key: 'assessmentOpinions',
            level: 'error',
            message: '预备党员考察表应包含2个考察意见：半年期考察和满一年考察'
        });
    } else {
        const joinPartyDate = parseDate(av?.branchMeetingSignatureDate);
        if (joinPartyDate) {
            // 验证半年期考察
            const halfYearExpected = addMonths(joinPartyDate, 6);
            const halfYearActual = parseDate(pa.assessmentOpinions[0]?.branchOpinionDate);
            
            if (!halfYearActual) {
                verifyMember.probationaryAssessment.push({
                    key: 'assessmentOpinions[0]',
                    level: 'info',
                    message: `半年期考察意见日期未填写，应在${formatDate(halfYearExpected)}左右（入党后6个月）`
                });
            } else if (Math.abs(daysBetween(halfYearActual, halfYearExpected)) > 30) {
                verifyMember.probationaryAssessment.push({
                    key: 'assessmentOpinions[0]',
                    level: 'error',
                    message: `半年期考察时间偏差过大：当前日期${formatDate(halfYearActual)}，应在${formatDate(halfYearExpected)}附近（±30天内）`
                });
            } else {
                verifyMember.probationaryAssessment.push({
                    key: 'assessmentOpinions[0]',
                    level: 'success',
                    message: `半年期考察时间正确（${formatDate(halfYearActual)}），符合入党后6个月要求`
                });
            }
            
            // 验证满一年考察
            const oneYearExpected = addMonths(joinPartyDate, 12);
            const oneYearActual = parseDate(pa.assessmentOpinions[1]?.branchOpinionDate);
            
            if (!oneYearActual) {
                verifyMember.probationaryAssessment.push({
                    key: 'assessmentOpinions[1]',
                    level: 'info',
                    message: `满一年考察意见日期未填写，应在${formatDate(oneYearExpected)}左右（入党后12个月）`
                });
            } else if (Math.abs(daysBetween(oneYearActual, oneYearExpected)) > 30) {
                verifyMember.probationaryAssessment.push({
                    key: 'assessmentOpinions[1]',
                    level: 'error',
                    message: `满一年考察时间偏差过大：当前日期${formatDate(oneYearActual)}，应在${formatDate(oneYearExpected)}附近（±30天内）`
                });
            } else {
                verifyMember.probationaryAssessment.push({
                    key: 'assessmentOpinions[1]',
                    level: 'success',
                    message: `满一年考察时间正确（${formatDate(oneYearActual)}），符合入党后12个月要求`
                });
            }
        } else {
            verifyMember.probationaryAssessment.push({
                key: 'assessmentOpinions',
                level: 'warning',
                message: '无法验证预备党员考察时间要求，请先填写入党志愿书中的支部大会决议日期'
            });
        }
    }
    
    // 16. 验证预备期思想汇报
    verifyMember.probationaryThoughtReports = [];
    
    if (!member.probationaryThoughtReports || member.probationaryThoughtReports.length === 0) {
        verifyMember.probationaryThoughtReports.push({
            key: 'probationaryThoughtReports',
            level: 'info',
            message: '预备期思想汇报未填写，应从入党开始每3个月提交一份'
        });
    } else {
        const joinPartyDate = av?.branchMeetingSignatureDate;
        const conversionDate = av?.probationaryConversionResolutionDate;
        
        if (joinPartyDate && conversionDate) {
            const checkResult = checkQuarterlyReports(
                member.probationaryThoughtReports,
                joinPartyDate,
                conversionDate
            );
            
            if (!checkResult.isValid) {
                verifyMember.probationaryThoughtReports.push({
                    key: 'probationaryThoughtReports',
                    level: 'error',
                    message: `预备期思想汇报不足：从${formatDate(joinPartyDate)}到${formatDate(conversionDate)}期间应有${checkResult.totalPeriods}份汇报，实际${checkResult.actualReports}份`
                });
                checkResult.missingPeriods.forEach((period, index) => {
                    verifyMember.probationaryThoughtReports.push({
                        key: `missing_probationary_${index}`,
                        level: 'error',
                        message: `缺少汇报时期：${period.start} 至 ${period.end}`
                    });
                });
            } else {
                verifyMember.probationaryThoughtReports.push({
                    key: 'probationaryThoughtReports',
                    level: 'success',
                    message: `预备期思想汇报完整（${checkResult.actualReports}份），符合每三个月一次的要求`
                });
            }
        } else {
            verifyMember.probationaryThoughtReports.push({
                key: 'probationaryThoughtReports',
                level: 'warning',
                message: '无法验证预备期思想汇报时间要求，请先填写入党志愿书中的相关日期'
            });
        }
    }
    
    // 17. 验证转正公示结果
    verifyMember.conversionPublicity = [];
    
    const cp = member.conversionPublicity;
    if (!cp?.startDate || !cp?.endDate) {
        verifyMember.conversionPublicity.push({
            key: 'conversionPublicity',
            level: 'info',
            message: '转正公示日期未填写，应在预备党员转正前进行5天公示'
        });
    } else {
        const startDate = parseDate(cp.startDate);
        const endDate = parseDate(cp.endDate);
        const days = daysBetween(startDate, endDate) + 1;
        
        if (days !== 5) {
            verifyMember.conversionPublicity.push({
                key: 'conversionPublicity',
                level: 'error',
                message: `转正公示时间不符合要求：当前公示${days}天（${formatDate(startDate)} - ${formatDate(endDate)}），应为5天`
            });
        } else {
            verifyMember.conversionPublicity.push({
                key: 'conversionPublicity',
                level: 'success',
                message: `转正公示时间正确（5天：${formatDate(startDate)} - ${formatDate(endDate)}）`
            });
        }
        
        // 验证是否在预备党员转正决议日期之前
        if (av?.probationaryConversionResolutionDate) {
            const conversionDate = parseDate(av.probationaryConversionResolutionDate);
            
            if (endDate >= conversionDate) {
                verifyMember.conversionPublicity.push({
                    key: 'endDate',
                    level: 'error',
                    message: `转正公示时间安排错误：公示结束日期${formatDate(endDate)}，应在预备党员转正决议日期（${formatDate(conversionDate)}）之前完成`
                });
            } else {
                verifyMember.conversionPublicity.push({
                    key: 'endDate',
                    level: 'success',
                    message: `转正公示时间安排正确，在转正决议前完成`
                });
            }
        }
    }
    
    return verifyMember;
}